package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.navigation.NavigationView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private TextView textbeta;
    private ImageView imageView;
    private ImageView further_image;
    private TextView nameTextView;
    private Button about_button;
    private Button out_btn;
    private Button fingerprint;
    private ViewPager viewPager;
    private ImageView name_image;
    private TextView name_text;
    private Button random_password;
    private ImageView switch_theme;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    private static final int PICK_IMAGE_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_home);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化视图
        initViews();
        initThere();

        // 初始化广播接收器
        initBroadcastReceiver();

        // 设置监听器
        setupListeners();

        // 加载数据
        loadNavigationView();
        loadSavedImage();
    }

    private void initThere() {
        // 接收当前的主题，设置switch_theme当前的图标
        File themeFile = new File(getFilesDir(), "theme.txt");
        try {
            if (themeFile.exists()) {
                // 读取文件内容
                FileInputStream fis = new FileInputStream(themeFile);
                byte[] bytes = new byte[(int) themeFile.length()];
                fis.read(bytes);
                fis.close();
                String currentTheme = new String(bytes);

                // 根据当前主题设置应用主题和图标
                if ("dark".equals(currentTheme)) {
                    // 设置深色主题
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    // 设置月亮图标
                    if (switch_theme != null) {
                        switch_theme.setBackgroundResource(R.drawable.dark);
                    }
                } else {
                    // 设置浅色主题（默认）
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    // 设置太阳图标
                    if (switch_theme != null) {
                        switch_theme.setBackgroundResource(R.drawable.sun);
                    }
                }
            } else {
                // 如果文件不存在，创建默认主题文件（浅色主题）
                createDefaultTheme();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 发生错误时使用默认主题（浅色主题）
            createDefaultTheme();
        }
    }

    // 创建默认主题（浅色主题）
    private void createDefaultTheme() {
        try {
            // 创建主题文件并写入默认值
            File themeFile = new File(getFilesDir(), "theme.txt");
            FileOutputStream fos = new FileOutputStream(themeFile);
            fos.write("sun".getBytes());  // 默认使用浅色主题
            fos.close();

            // 设置默认主题
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            // 设置太阳图标
            if (switch_theme != null) {
                switch_theme.setBackgroundResource(R.drawable.sun);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initViews() {
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        imageView = findViewById(R.id.image_view);
        textbeta = findViewById(R.id.textviews);
        about_button = findViewById(R.id.about_button);
        out_btn = findViewById(R.id.out_btn);
        further_image = findViewById(R.id.further_image);
        viewPager = findViewById(R.id.view_pager);
        fingerprint = findViewById(R.id.fingerprint);
        name_image = findViewById(R.id.name_image);
        name_text = findViewById(R.id.name_text);
        random_password = findViewById(R.id.random_password);
        switch_theme = findViewById(R.id.switch_theme);
    }

    private void initBroadcastReceiver() {
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);
    }

    private void setupListeners() {
        imageView.setOnClickListener(v -> drawerLayout.openDrawer(navigationView));
        further_image.setOnClickListener(v -> showOptionMenu());
        out_btn.setOnClickListener(v -> out_btn());
        about_button.setOnClickListener(v -> about_button());
        fingerprint.setOnClickListener(v -> fingerprint());
        random_password.setOnClickListener(v -> random_password());
        switch_theme.setOnClickListener(v -> switchTheme());
        name_image.setOnClickListener(v -> nameImage());
        name_image.setClipToOutline(true);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
    }

    private void nameImage() {
        //Toast.makeText(this, "点击了头像", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);

        // 发送打开图片选择器广播
        Intent pickerIntent = new Intent("IMAGE_PICKER_OPENED");
        localBroadcastManager.sendBroadcast(pickerIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (themeChangeReceiver != null && localBroadcastManager != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private void switchTheme() {
        // 1. 读取当前主题
        File themeFile = new File(getFilesDir(), "theme.txt");
        String currentTheme = "sun"; // 默认浅色主题

        try {
            if (themeFile.exists()) {
                FileInputStream fis = new FileInputStream(themeFile);
                byte[] bytes = new byte[(int) themeFile.length()];
                fis.read(bytes);
                fis.close();
                currentTheme = new String(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 2. 切换主题
        String newTheme;
        int newIcon;
        int nightMode;

        if ("sun".equals(currentTheme)) {
            // 当前是浅色主题，切换到深色主题
            newTheme = "dark";
            newIcon = R.drawable.dark;
            nightMode = AppCompatDelegate.MODE_NIGHT_YES;
        } else {
            // 当前是深色主题，切换到浅色主题
            newTheme = "sun";
            newIcon = R.drawable.sun;
            nightMode = AppCompatDelegate.MODE_NIGHT_NO;
        }

        // 3. 更新主题文件
        try {
            FileOutputStream fos = new FileOutputStream(themeFile);
            fos.write(newTheme.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 4. 更新应用主题
        AppCompatDelegate.setDefaultNightMode(nightMode);

        // 5. 更新图标（带动画效果）
        if (switch_theme != null) {
            switch_theme.animate()
                    .scaleX(0.8f)
                    .scaleY(0.8f)
                    .setDuration(100)
                    .withEndAction(() -> {
                        switch_theme.setBackgroundResource(newIcon);
                        switch_theme.animate()
                                .scaleX(1f)
                                .scaleY(1f)
                                .setDuration(100)
                                .start();
                    })
                    .start();
        }

        // 6. 发送广播通知其他Activity更新主题
        Intent intent = new Intent("THEME_CHANGED");
        intent.putExtra("theme", newTheme);
        localBroadcastManager.sendBroadcast(intent);
    }



    private void random_password() {
        // 跳转到RandomActivity
        Intent intent = new Intent(HomeActivity.this, RandomActivity.class);
        startActivity(intent);
        // 关闭HomeActivity
        //finish();
    }

    private void about_button() {
        // 跳转到AboutActivity
        Intent intent = new Intent(HomeActivity.this, AboutActivity.class);
        startActivity(intent);

    }

    private void loadNavigationView() {
        // 设置侧边栏的头像name_image和名称name_text
        SharedPreferences sharedPreferences = getSharedPreferences("SavedImage", Context.MODE_PRIVATE);
        String imagePath = sharedPreferences.getString("image_path", null);
        if (imagePath != null && new File(imagePath).exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            name_image.setImageBitmap(bitmap);
            name_image.setClipToOutline(true);
        }
        String username = getIntent().getStringExtra("username");
        name_text.setText(username);
        textbeta.setText(username);
    }


    // MyPagerAdapter 类的定义
    public class MyPagerAdapter extends FragmentPagerAdapter {
        public final List<Fragment> fragments = new ArrayList<>();

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments.add(new ListActivity());
            fragments.add(new PasswdActivity());
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    public interface DataRefreshListener {
        void refreshData();
    }
    //以下是按钮添加区域
    private void fingerprint() {
        FingerprintLogin fingerprintLogin = new FingerprintLogin(this, new FingerprintLogin.AuthenticationCallback() {
            @Override
            public void onAuthenticationResult(boolean success) {
                if (success) {
//                    Toast.makeText(HomeActivity.this, "11111", Toast.LENGTH_SHORT).show();
                    // 创建true文件，用于判断是否已经验证过指纹，什么都不写入
                    File file = new File(getFilesDir(), "true");
                    try {
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // 发送指纹验证成功的广播
                    Intent intent = new Intent("FINGERPRINT_AUTH_SUCCESS");
                    localBroadcastManager.sendBroadcast(intent);
                } else {
                    Toast.makeText(HomeActivity.this, "指纹验证失败", Toast.LENGTH_SHORT).show();

                    // 发送指纹验证失败的广播
                    Intent intent = new Intent("FINGERPRINT_AUTH_FAILED");
                    localBroadcastManager.sendBroadcast(intent);
                }
            }
        });
        fingerprintLogin.authenticate();
    }

    private void showOptionMenu() {
        PopupMenu popupMenu = new PopupMenu(this, further_image);
        popupMenu.getMenuInflater().inflate(R.menu.menu_optionmenu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(item -> handleMenuItemSelection(item));
        popupMenu.show();
    }

    private boolean handleMenuItemSelection(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.backup) {
            backupDatabase();
            return true;
        } if (itemId == R.id.restore) {
            // 当选择的文件名为Notepad时，恢复的为Notepad;，当文件名为Passwd_Notepad时,恢复的为Passwd_Notepad
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 2);
            return true;
        } else {
            return false;
        }
    }

    private void backupDatabase() {
        // 获取本应用数据库文件的路径
        File dbFile = getDatabasePath("mmb.db");
        // 设置备份文件的名称和路径
        File backupFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "密码本备份.mmb");

        // 检查源数据库文件是否存在
        if (dbFile.exists()) {
            // 读取dbFile并写入到backupFile
            try (InputStream inputStream = new FileInputStream(dbFile);
                 OutputStream outputStream = new FileOutputStream(backupFile)) {

                byte[] buffer = new byte[1024];
                int length;
                // 复制文件内容
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }

                // 输出备份成功的信息
                Toast.makeText(this, "数据库备份成功！位置:/storage/emulated/0/Download", Toast.LENGTH_SHORT).show();

                // 发送数据库备份成功的广播
                Intent intent = new Intent("DATABASE_BACKUP_SUCCESS");
                localBroadcastManager.sendBroadcast(intent);
            } catch (IOException e) {
                e.printStackTrace();
                // 输出备份失败的信息
                Toast.makeText(this, "数据库备份失败", Toast.LENGTH_SHORT).show();

                // 发送数据库备份失败的广播
                Intent intent = new Intent("DATABASE_BACKUP_FAILED");
                localBroadcastManager.sendBroadcast(intent);
            }
        } else {
            // 输出数据库文件不存在的信息
            Toast.makeText(this, "数据库文件不存在", Toast.LENGTH_SHORT).show();

            // 发送数据库不存在的广播
            Intent intent = new Intent("DATABASE_NOT_FOUND");
            localBroadcastManager.sendBroadcast(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        // 处理图片选择结果
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            try {
                // 获取图片位图
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);

                // 更新头像显示
                name_image.setImageBitmap(bitmap);
                imageView.setImageBitmap(bitmap);

                // 保存图片到本地存储
                String imagePath = saveImageToInternalStorage(bitmap);

                // 保存图片路径到SharedPreferences
                SharedPreferences sharedPreferences = getSharedPreferences("SavedImage", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("image_path", imagePath);
                editor.apply();

                Toast.makeText(this, "头像更新成功", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "头像更新失败", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode==1&&resultCode==2){
//            showQueryData();
            notifyDataRefresh();
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 2) { // 恢复文件
                Uri selectedFileUri = data.getData();
                try {
                    InputStream inputStream = getContentResolver().openInputStream(selectedFileUri);
                    File dbFile = getDatabasePath("mmb.db");
                    OutputStream outputStream = new FileOutputStream(dbFile);
                    byte[] buffer = new byte[1024];
                    int length;
                    // 复制文件内容
                    while ((length = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();

                    // 输出恢复成功的信息
                    Toast.makeText(this, "恢复完成！" , Toast.LENGTH_SHORT).show();
//                    showQueryData();
                    notifyDataRefresh();

                    // 发送数据库恢复成功的广播
                    Intent intent = new Intent("DATABASE_RESTORE_SUCCESS");
                    localBroadcastManager.sendBroadcast(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                    // 输出恢复失败的信息
                    Toast.makeText(this, "文件恢复失败", Toast.LENGTH_SHORT).show();

                    // 发送数据库恢复失败的广播
                    Intent intent = new Intent("DATABASE_RESTORE_FAILED");
                    localBroadcastManager.sendBroadcast(intent);
                }
            }
        }
    }

    private String saveImageToInternalStorage(Bitmap bitmap) {
        String path = null;
        try {
            // 使用固定的文件名
            File file = new File(getFilesDir(), "profile_image.jpg");

            // 压缩并保存图片
            FileOutputStream out = new FileOutputStream(file);
            // 使用JPEG格式，质量设置为85%，在保持图片质量的同时减小文件大小
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
            out.flush();
            out.close();

            // 返回文件的绝对路径
            path = file.getAbsolutePath();

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show();
        }
        return path;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_optionmenu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void out_btn() {
        // 退出登录, 返回到登录界面, 清除保存的用户名和密码
        SharedPreferences sharedPreferences = getSharedPreferences("SavedCredentials", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        // 之所以用的是password，是因为在混淆的时候，我们将用户名和密码的变量名进行了混淆，username -> password，password -> username
        editor.remove("password");
        editor.apply();

        // 发送用户退出登录的广播
        Intent intent = new Intent("USER_LOGOUT");
        localBroadcastManager.sendBroadcast(intent);

        Intent loginIntent = new Intent(this, LoginActivity.class);
        startActivity(loginIntent);
        finish();
    }

    private void setupDrawerHeader(NavigationView navigationView) {
        View headerView = navigationView.getHeaderView(0);
        nameTextView = headerView.findViewById(R.id.name_text);
    }

    private void loadSavedImage() {
        SharedPreferences sharedPreferences = getSharedPreferences("SavedImage", Context.MODE_PRIVATE);
        String imagePath = sharedPreferences.getString("image_path", null);
        if (imagePath != null && new File(imagePath).exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            imageView.setImageBitmap(bitmap);
            imageView.setClipToOutline(true);
        }
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                menuItem -> {
                    // 处理菜单项点击事件
                    menuItem.setChecked(true);
                    drawerLayout.closeDrawers();
                    return true;
                }
        );
    }

    private void notifyDataRefresh() {
        MyPagerAdapter adapter = (MyPagerAdapter) viewPager.getAdapter();
        for (Fragment fragment : adapter.fragments) {
            if (fragment instanceof DataRefreshListener) {
                ((DataRefreshListener) fragment).refreshData();
            }
        }

        // 发送数据刷新的广播
        Intent intent = new Intent("DATA_REFRESH");
        localBroadcastManager.sendBroadcast(intent);
    }
}
